package com.ibpd.henuocms.web.controller.manage;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.dao.impl.HqlParameter;
import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.NodeFormEntity;
import com.ibpd.henuocms.entity.NodeFormFieldEntity;
import com.ibpd.henuocms.entity.ext.NodeFormExtEntity;
import com.ibpd.henuocms.service.node.INodeService;
import com.ibpd.henuocms.service.node.NodeServiceImpl;
import com.ibpd.henuocms.service.nodeForm.INodeFormFieldService;
import com.ibpd.henuocms.service.nodeForm.INodeFormService;
import com.ibpd.henuocms.service.nodeForm.NodeFormFieldServiceImpl;
import com.ibpd.henuocms.service.nodeForm.NodeFormServiceImpl;

@Controller
public class NodeForm extends BaseController {
	Logger log=Logger.getLogger(NodeForm.class);
	@RequestMapping("Manage/NodeForm/index.do")
	public String index(String nodeId,String type,org.springframework.ui.Model model) throws IOException{
		model.addAttribute("nodeId",nodeId);
		model.addAttribute("type",type);
		return "manage/nodeForm/index";
	}	

	@RequestMapping("Manage/NodeForm/getFormList.do")
	public void getFormList(HttpServletRequest req,HttpServletResponse resp,Long nodeId,String type) throws IOException{
		INodeFormService nfService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
		Integer tp=NodeFormEntity.FORMTYPE_NODEFORM;
		if(type!=null){
			if(!type.trim().toLowerCase().equals("node")){
				tp=NodeFormEntity.FORMTYPE_CONTENTFORM;
			}
		}
//		nfService.getDao().clearCache();
		JSONArray json=JSONArray.fromObject(nfService.getList("from "+nfService.getTableName()+" where formType="+tp, null));
		super.printJsonData(resp, json.toString());
	}
	@RequestMapping("Manage/NodeForm/check.do")
	public void check(HttpServletRequest req,HttpServletResponse resp,Long nodeId,String type) throws IOException{
		NodeFormExtEntity nodeFormExt=getNodeFormExtEntity(nodeId,type);
		if(nodeFormExt==null){
			super.printMsg(resp, "-1", "-1", "该栏目尚未对应的表单.");
		}else{
			super.printMsg(resp, "99", "-1", "该栏目尚未对应的表单.");
		}
	}
	@RequestMapping("Manage/NodeForm/toAdd.do")
	public String toAdd(HttpServletRequest req,HttpServletResponse resp,Long nodeId,String type,org.springframework.ui.Model model) throws IOException{
		model.addAttribute("nodeId",nodeId);
		model.addAttribute("type",type);
		return "manage/nodeForm/add";
	}
	private void setFieldMode(HttpServletResponse resp,String ids,String type) throws IOException{
		ids=(ids==null)?"":ids;
		if(StringUtils.isBlank(ids)){
			printParamErrorMsg(resp);
			return;
		}
		String[] idss=ids.split(",");
		INodeFormFieldService nfService=(INodeFormFieldService) getService(NodeFormFieldServiceImpl.class);
		String whereString="";
		List<HqlParameter> hqlList=new ArrayList<HqlParameter>();
		for(Integer i=0;i<idss.length;i++){
			whereString+="id=:id"+i+" or ";
			hqlList.add(new HqlParameter("id"+i,Long.valueOf(idss[i]),HqlParameter.DataType_Enum.Long));
		}
		if(hqlList.size()>0){
			whereString="from "+nfService.getTableName()+" where "+whereString.substring(0,whereString.length()-4);
		}else{
			super.printMsg(resp, "-2", "-2", "没有选中行?");
			return;	
		}
		List<NodeFormFieldEntity> fieldList=nfService.getList(whereString, hqlList);
		for(NodeFormFieldEntity field:fieldList){
			if(type.trim().equals("readOnlyByAddMode"))
				field.setWriteByAddMode(!field.getWriteByAddMode());
			else if(type.trim().equals("readOnlyByEditMode")){
				field.setWriteByEditMode(!field.getWriteByAddMode());
			}else if(type.trim().equals("hiddenByAddMode")){
				field.setDisplayByAddMode(!field.getDisplayByAddMode());
			}else if(type.trim().equals("hiddenByEditMode")){
				field.setDisplayByEditMode(!field.getDisplayByEditMode());
			}
			nfService.saveEntity(field);
		}
		printDefaultSuccessMsg(resp);
	}
	@RequestMapping("Manage/NodeForm/readOnlyByAddMode.do")
	public void readOnleyByAddMode(Model model,HttpServletResponse resp,String ids) throws IOException{
		setFieldMode(resp,ids,"readOnlyByAddMode");
	}
	@RequestMapping("Manage/NodeForm/readOnlyByEditMode.do")
	public void readOnleyByEditMode(Model model,HttpServletResponse resp,String ids) throws IOException{
		setFieldMode(resp,ids,"readOnlyByEditMode");
	}
	@RequestMapping("Manage/NodeForm/hiddenByAddMode.do")
	public void hiddenByAddMode(Model model,HttpServletResponse resp,String ids) throws IOException{
		setFieldMode(resp,ids,"hiddenByAddMode");
	}
	@RequestMapping("Manage/NodeForm/hiddenByEditMode.do")
	public void hiddenByEditMode(Model model,HttpServletResponse resp,String ids) throws IOException{
		setFieldMode(resp,ids,"hiddenByEditMode");
	}
	@RequestMapping("Manage/NodeForm/props.do")
	public String props(Long fieldId,String type,Model model,HttpServletResponse resp) throws IOException{
		//检索出nodeForm和NodeFormField然后压入前台
		Integer tp=NodeFormEntity.FORMTYPE_NODEFORM;
		if(type!=null){
			if(!type.trim().toLowerCase().equals("node")){
				tp=NodeFormEntity.FORMTYPE_CONTENTFORM;
			}
		}
		INodeFormFieldService fieldService=(INodeFormFieldService) ServiceProxyFactory.getServiceProxy(NodeFormFieldServiceImpl.class);
		NodeFormFieldEntity field=fieldService.getEntityById(fieldId);
		if(field==null){
			super.printJsonData(resp, super.getJsonResult("-1", "-1", "没有对应的field"));
			return super.ERROR_PAGE;
		}
		Long formId=field.getNodeFormId();
		INodeFormService nfService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
		NodeFormExtEntity extForm=nfService.getNodeForm(tp, null,formId);
		model.addAttribute("nodeForm",extForm);
		model.addAttribute("nodeFormField",field);
		return "manage/nodeForm/props";
	}
	@RequestMapping("Manage/NodeForm/saveProp.do")
	public void saveProp(Long fieldId,String field,String value,HttpServletResponse resp) throws IOException{
		log.debug("saveprop.do:"+fieldId+" "+field+" "+value);
		if(fieldId==null){
			super.printJsonData(resp, super.getJsonResult("-1", "-1", "fieldId为空"));
			return;
		}
		INodeFormFieldService fieldService=(INodeFormFieldService) ServiceProxyFactory.getServiceProxy(NodeFormFieldServiceImpl.class);
		NodeFormFieldEntity fieldEntity=fieldService.getEntityById(fieldId);
		if(fieldEntity==null){
			super.printJsonData(resp, super.getJsonResult("-6", "-6", "fieldEntity为空"));
			return;
		}
		if(field.indexOf("nodeForm_")!=-1){
			//处理form信息的保存
			Long formId=fieldEntity.getNodeFormId();
			field=field.replace("nodeForm_", "");
			//下面用反射的办法来处理数据的保存
			String mtName="set"+field.substring(0,1).toUpperCase()+field.substring(1);
			try {
				INodeFormService nfService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
				NodeFormEntity form=nfService.getEntityById(formId);
				if(form==null){
					super.printJsonData(resp, super.getJsonResult("-2", "-2", "form为空"));
					return;
				}
				mtName="get"+field.substring(0,1).toUpperCase()+field.substring(1);
				Method mhd=form.getClass().getMethod(mtName, new Class[]{});
				if(mhd==null){
					super.printJsonData(resp, super.getJsonResult("-2", "-1", "Method为空"));
					return;
				}
				mtName="set"+field.substring(0,1).toUpperCase()+field.substring(1);
				Method method=form.getClass().getMethod(mtName, new Class[]{mhd.getReturnType()});
				if(method==null){
					super.printJsonData(resp, super.getJsonResult("-4", "-4", "metod为空"));
					return;
				}
				method.invoke(form, getValue(value,mhd.getReturnType().getSimpleName()));
				nfService.saveEntity(form);
				super.printJsonData(resp, super.getJsonResult("99", "99", "保存成功"));
				
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			//处理field信息的保存
			try {
				
				String mtName="get"+field.substring(0,1).toUpperCase()+field.substring(1);
				Method mhd=fieldEntity.getClass().getMethod(mtName, new Class[]{});
				if(mhd==null){
					super.printJsonData(resp, super.getJsonResult("-2", "-1", "Method为空"));
					return;
				}
				mtName="set"+field.substring(0,1).toUpperCase()+field.substring(1);
				Method method=fieldEntity.getClass().getMethod(mtName, new Class[]{mhd.getReturnType()});
				if(method==null){
					super.printJsonData(resp, super.getJsonResult("-9", "-9", "metod为空"));
					return;
				}
				method.invoke(fieldEntity, getValue(value,mhd.getReturnType().getSimpleName()));
				fieldService.saveEntity(fieldEntity);
				super.printJsonData(resp, super.getJsonResult("99", "99", "保存成功"));

			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	@RequestMapping("Manage/NodeForm/init.do")
	public void initDefaultNodeForm(HttpServletResponse resp) throws IOException{
		INodeFormService nfService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
		nfService.initDefaultNodeForm();
		nfService.initDefaultContentForm();
		super.printJsonData(resp, "ok");
	}
	@RequestMapping("Manage/NodeForm/doAdd.do")
	public void doAdd(HttpServletRequest req,HttpServletResponse resp,Long nodeId,String type,String addType,Long formId) throws IOException{
		INodeFormService nfService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
		Integer tp=NodeFormEntity.FORMTYPE_NODEFORM;
		if(type!=null){
			if(!type.trim().toLowerCase().equals("node")){
				tp=NodeFormEntity.FORMTYPE_CONTENTFORM;
			}
		}
		nfService.UnLinkNodeForm(nodeId,tp);
		//useDefault new link
		//如果是默认的，那么就做一个node-nodeForm对照为nodeId:-1的对照 	
		//如果是new，那么全新新建
		//如果是link，就链接一下
		addType=addType.trim().toLowerCase();
		if(addType.equals("usedefault")){
			nfService.linkNodeForm(nodeId, -1L);
		}else if(addType.equals("new")){
			INodeService nodeService=(INodeService) ServiceProxyFactory.getServiceProxy(NodeServiceImpl.class);
			//如果是全新新建，那么这里在新建以前需要将旧的对照删除
			NodeEntity n=nodeService.getEntityById(nodeId);
			NodeFormEntity nodeForm=new NodeFormEntity();
			nodeForm.setCreateTime(new Date());
			if(tp==NodeFormEntity.FORMTYPE_NODEFORM)
				nodeForm.setFormName(n!=null?n.getText()+"的栏目表单":nodeId+"'s node form");
			else
				nodeForm.setFormName(n!=null?n.getText()+"的内容表单":nodeId+"'s cnt form");
			nodeForm.setFormType(tp);
			nodeForm.setIsDefault(false);
			nodeForm.setNodeId(nodeId);
			nodeForm.setOrder(0);
			nodeForm.setUpdateTime(new Date());
			nfService.addNewNodeForm(nodeId, nodeForm,tp);
			
		}else if(addType.equals("link")){
			nfService.linkNodeForm(nodeId, formId);
		}else{
			super.printMsg(resp, "-1", "-1", "参数不正确");
		}
		super.printMsg(resp, "99", "-1", "设置表单成功");
	}
	private NodeFormExtEntity getNodeFormExtEntity(Long nodeId,String type){
		INodeFormService nfService=(INodeFormService) ServiceProxyFactory.getServiceProxy(NodeFormServiceImpl.class);
		Integer tp=NodeFormEntity.FORMTYPE_NODEFORM;
		if(type!=null){
			if(!type.trim().toLowerCase().equals("node")){
				tp=NodeFormEntity.FORMTYPE_CONTENTFORM;
			}
		}
		NodeFormExtEntity nodeFormExt=nfService.getNodeForm(tp, nodeId,null);
		return nodeFormExt;
	}
	
	@RequestMapping("Manage/NodeForm/getFieldList.do")
	public void getFieldList(HttpServletRequest req,HttpServletResponse resp,Long nodeId,String type) throws IOException{
		NodeFormExtEntity nodeFormExt=getNodeFormExtEntity(nodeId,type);
		if(nodeFormExt==null){
			super.printJsonData(resp, "{}");
		}else{
			JSONArray jsonArray = JSONArray.fromObject( nodeFormExt.getNodeFormFieldList() );
			super.printJsonData(resp,jsonArray.toString());
		}
	}
}
